package sf

import (
	"fmt"
	"github.com/bwmarrin/snowflake"
	"net"
	"time"
)

// GenSnowflakeID 生成雪花算法ID
func GenSnowflakeID() int64 {
	ip, err := getLocalIP()
	if err != nil {
		fmt.Println("Error getting local IP:", err)
		return 0
	}

	// 将IP地址转换为整数，作为节点ID
	var nodeID int64
	for _, b := range net.ParseIP(ip).To4() {
		nodeID = nodeID<<8 + int64(b)
	}

	var node *snowflake.Node
	var st time.Time
	st, _ = time.Parse("2006-01-02", "2023-07-07")
	snowflake.Epoch = st.UnixNano() / 1000000
	node, _ = snowflake.NewNode(nodeID % 777)
	return node.Generate().Int64()
}

func getLocalIP() (string, error) {
	addrs, err := net.InterfaceAddrs()
	if err != nil {
		return "", err
	}

	for _, addr := range addrs {
		ipNet, ok := addr.(*net.IPNet)
		if ok && !ipNet.IP.IsLoopback() && ipNet.IP.To4() != nil {
			return ipNet.IP.String(), nil
		}
	}

	return "", fmt.Errorf("failed to get local IP address")
}

// GenSnowflakeID 生成雪花算法ID
func GenSnowflakeStringID() string {
	ip, err := getLocalIP()
	if err != nil {
		fmt.Println("Error getting local IP:", err)
		return ""
	}

	// 将IP地址转换为整数，作为节点ID
	var nodeID int64
	for _, b := range net.ParseIP(ip).To4() {
		nodeID = nodeID<<8 + int64(b)
	}

	var node *snowflake.Node
	var st time.Time
	st, _ = time.Parse("2006-01-02", "2023-07-07")
	snowflake.Epoch = st.UnixNano() / 1000000
	node, _ = snowflake.NewNode(nodeID % 777)
	return node.Generate().String()
}
